package cn.janescott.file.server.util;

import cn.janescott.file.server.exception.MyException;
import cn.janescott.file.server.exception.MyExceptionEnums;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * io操作
 *
 * @author scott
 * @date 2019/3/8
 */
public final class IoUtil {

    private static Logger logger = LoggerFactory.getLogger(IoUtil.class);

    /**
     * 流转换
     *
     * @param in         输入流
     * @param out        输出流
     * @param bufferSize 缓冲区大小
     */
    public static void transfer(InputStream in, OutputStream out, int bufferSize) {
        try {
            byte[] data = new byte[bufferSize];
            int length;
            while ((length = in.read(data)) > 0) {
                out.write(data, 0, length);
                out.flush();
            }
        } catch (IOException io) {
            logger.error(io.getMessage(), io);
            throw MyException.failed(MyExceptionEnums.IO_EXCEPTION, io);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException io) {
                }
            }
        }
    }

    /**
     * 流转换
     *
     * @param in
     * @param out
     */
    public static void transfer(InputStream in, OutputStream out) {
        transfer(in, out, DEFAULT_BUFFER_SIZE);
    }

    /**
     * 默认缓冲区大小
     */
    private static final int DEFAULT_BUFFER_SIZE = 1024;
}
